<template>
  <div>

  </div>
</template>

<script>
export default {
  name: "Socket",
  date() {
    return {}
  },
  mounted() {
    this.initWebSocket();
  },
  methods: {
    initWebSocket() {
      console.log(this.$parent)
      let name = this.$store.state.user.name;
      let wsUrl = process.env.VUE_APP_BASE_WS + '/socket/' + name;
      if (typeof (WebSocket) === "undefined") {
        alert("您的浏览器不支持socket")
      } else {
        // 实例化socket
        this.socket = new WebSocket(wsUrl)
        // 监听socket连接
        this.socket.onopen = this.open
        // 监听socket错误信息
        this.socket.onerror = this.error
        // 监听socket消息
        this.socket.onmessage = this.getMessage
      }
    },

    open() {
      console.log("socket连接成功")
    },
    error() {
      console.log("连接错误")
    },
    getMessage(msg) {
      console.log(msg.data)
      // 将字符串转成对象
      let restVo = JSON.parse(msg.data)
      if(restVo.type === '1'){
        console.log(restVo.message)
      }
      // 如果是是状态信息
      if(restVo.type === '2'){
        if(typeof this.$parent.initStateMarker === 'function'){
          this.$parent.initStateMarker();
        }

      }
      // 如果是要素消息
      if(restVo.type === '3'){
        if(typeof this.$parent.initSurfMinMarker === 'function'){
          this.$parent.initSurfMinMarker();
        }
      }
    },
    send(message) {
      console.log("发送消息:" + message)
    },
    close() {
      console.log("socket已经关闭")
    }
  },
  destroyed() {
    // 销毁监听
    this.socket.onclose = this.close
  }
}
</script>

<style scoped>

</style>
